package com.ruoyi.web.controller.monitor;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class UploadTool {
    public static String fileupload(MultipartFile multipartFile, String filepath) throws IOException {
        if (multipartFile.getOriginalFilename() == null || multipartFile.getOriginalFilename().equals("")) {
            return null;
        }
        //生成一个随机的文件名
        String filName = UUID.randomUUID().toString();
        //获取文件名
        String orName = multipartFile.getOriginalFilename();
        //获取文件后缀
        String exName = orName.substring(orName.lastIndexOf("."));
        //拼接上传的文件夹
        String dirName ="/upload/"+filepath + "/";
        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(UploadTool.class);
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        String dirPath = jarF.getParentFile().toString()+dirName;
        File filePath=new File(dirPath);
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        filName += exName;
        File orfile = new File(filePath, filName);
        multipartFile.transferTo(orfile);
        return dirName + filName;
    }

    public static void deletefile(String files) {
        if (files != null || !files.equals("")) {
            //获取jar包所在目录
            ApplicationHome h = new ApplicationHome(UploadTool.class);
            File jarF = h.getSource();
            //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
            String dirPath = jarF.getParentFile().toString();
            System.out.println("filepath:++"+dirPath+files);
            File file = new File(dirPath,files);
            if (file.exists()) {
                file.delete();
            }
        }
    }
}
